<template>
    <div class="innerContainer">
        <common-title>
            <template #expand>
                <el-button type="primary" @click="onEidt()">添加任务</el-button>
            </template>
        </common-title>

        <div class="innerPane">
            <div class="filterArea">
                <el-form :inline="true" :model="filterForm" class="demo-form-inline">
                    <el-form-item label="断面编码">
                        <el-input @keyup.enter="search" v-model="searchForm.taskName" placeholder="请输入断面编码"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <el-button plain type="primary" @click="search">查询</el-button>
                        <el-button plain @click="onClear">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <el-table :data="tableData" border row-key="id" style="width: 100%;  " row-class-name="fixed-row"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column type="index" width="50" label="序号" />
                <el-table-column header-align="center" prop="taskName" label="断面编码" width="160" />
                <el-table-column header-align="center" prop="taskDesc" label="线路ID" width="180" />
                <el-table-column header-align="center" prop="taskSeq" label="上/下行" width="120" />
                <el-table-column header-align="center" label="是否同步" width="100">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isPush" :active-value="1" :inactive-value="0"
                            :before-change="() => toggleSwitch(scope.row, 'isPush')" />
                    </template>
                </el-table-column>

                <el-table-column header-align="center" label="是否解包" width="120">
                    <template #default="scope">
                        <el-switch v-model="scope.row.isUnpack" :active-value="1" :inactive-value="0"
                            :before-change="() => toggleSwitch(scope.row, 'isUnpack')" />
                    </template>
                </el-table-column>
                <el-table-column header-align="center" prop="remark" label="备注" />

                <el-table-column label="操作" header-align="center" width="260" prop="col9">
                    <template #default="scope">
                        <el-link type="primary" size="small" @click="onEidt(scope.row)">编辑</el-link>

                        <el-link type="danger" size="small" @click="onDel(scope.row)">删除</el-link>

                        <el-link type="primary" size="small" @click="onAddEqui(scope.row)">添加设备</el-link>


                        <el-link type="primary" size="small" @click="handleExportTask(scope.row)">导出任务</el-link>

                        <el-link plain type="success" size="small" @click="onPublishMqtt(scope.row)">发布任务</el-link>

                        <el-link plain type="info" size="small" @click="handlerRemoteTask(scope.row)">远程任务</el-link>
                    </template>
                </el-table-column>


            </el-table>
            <!-- 分页 -->
            <el-pagination class="pagination" :current-page="searchForm.current" :page-size="searchForm.size"
                :page-sizes="[10, 50, 100, 200]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>



    <el-dialog v-model="topicDialogVisible" title="MQTT发布" width="800" style="height: 500px;">
        <el-input v-model="taskId" style="display: none;"></el-input>
        <el-input v-model="mqttTopic" placeholder="请输入mqtt topic"></el-input>

        <div class="json-box" style="margin-top: 10px; height:300px; border: 1px solid #eee; padding:10px;">
            <vue-json-pretty :data="taskString" />
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="topicDialogVisible = false">取消</el-button>

                <el-button @click="copySn(taskString)">复制内容</el-button>

                <el-button type="primary" @click="handlePublichMqtt">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="remoteTaskDialogVisible" title="MQTT远程任务" width="800" style="height: 500px;">
        <el-input v-model="remoteTask.remoteLastTaskTime"></el-input>

        <div class="json-box" style="margin-top: 10px; height:300px; border: 1px solid #eee; padding:10px;">
            <vue-json-pretty :data="remoteTask.remoteLastTaskJson" />
        </div>
        <template #footer>
            <div class="dialog-footer">

                <el-button @click="remoteTaskDialogVisible = false">取消</el-button>

                <el-button @click="copySn(remoteTask.remoteLastTaskJson)">复制内容</el-button>

            </div>
        </template>
    </el-dialog>
    <!-- 导入弹出层 -->
    <import-dialog ref="importDialog" @confirm="search"></import-dialog>

    <detail-view ref="viewObj" @confirm="search"></detail-view>

    <pre-view ref="previewObj" @confirm="search"></pre-view>
</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";

import ImportDialog from "@/components/ImportDialog.vue";

import DetailView from "./view.vue";

import PreView from "./preview.vue";

import { onMounted, reactive, ref } from "vue";

import VueJsonPretty from 'vue-json-pretty';
import 'vue-json-pretty/lib/styles.css';
import { useRouter } from "vue-router";

import { clienttaskList, clienttaskSave, clienttaskDel, clienttaskPublishMqtt, clienttaskMqttTopic, clienttaskRemoteTask, clienttaskExportTask } from "@/utils/requests";


import { ElMessage, ElMessageBox } from "element-plus";
import { tr } from "element-plus/es/locales.mjs";

const router = useRouter();

// Dom 挂载之后
onMounted(() => {
    search();
});

// 用户数据
let tableData = ref([]);

let total = ref(0);

// 搜索条件
const searchForm = reactive({
    current: 1,
    size: 10,
    taskName: "",
});

const onClear = () => {
    (searchForm.taskName = ""), search();
};

const toggleSwitch = async (row, field) => {
    try {
        let postData = { ...row };
        postData[field] = postData[field] === 1 ? 0 : 1;
        return await clienttaskSave(postData);

    } catch (e) {
        return false         // 阻止切换，自动回滚
    }
};


const handleSizeChange = (size) => {
    searchForm.size = size;
    search();
};
const handleCurrentChange = (current) => {
    searchForm.current = current;
    search();
};


const search = () => {
    searchForm.current = 1;

    clienttaskList(searchForm).then((res) => {
        tableData.value = res.records;

        total.value = res.total;
    });
};

const copySn = (val) => {
    const el = document.createElement('textarea');
    el.value = JSON.stringify(val, null, 2);
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    ElMessage.success('内容已复制到剪切板');
};

// 详情查看弹窗
const viewObj = ref();
const onEidt = (row) => {
    let rowData = null;
    if (row) {
        rowData = Object.assign({ _o: "w" }, row)
    }
    viewObj.value.openDialog(rowData);
};


let topicDialogVisible = ref(false);
let remoteTaskDialogVisible = ref(false);

const mqttTopic = ref("");
const taskString = ref("");
const taskId = ref("");

const remoteTask = reactive({});

const onPublishMqtt = (row) => {
    clienttaskMqttTopic({ taskId: row.id }).then((res) => {
        mqttTopic.value = res.topic;
        taskString.value = JSON.parse(res.taskString);
        taskId.value = row.id;
        topicDialogVisible.value = true;
    }).catch((e) => {
        ElMessage.error(e);
    });
};

const handlePublichMqtt = () => {
    clienttaskPublishMqtt({ taskId: taskId.value, topic: mqttTopic.value }).then(() => {
        ElMessage.success("发布成功");
        topicDialogVisible.value = false;
    }).catch(() => {
        ElMessage.error("发布失败");
    });
}
const handlerRemoteTask = (row) => {
    clienttaskRemoteTask({ taskId: row.id }).then((res) => {
        remoteTask["remoteLastTaskJson"] = JSON.parse(res.remoteLastTaskJson);
        remoteTask["remoteLastTaskTime"] = res.remoteLastTaskTime;
        remoteTaskDialogVisible.value = true;
    }).catch((e) => {
        ElMessage.error(e);
    });
};

const handleExportTask = (row) => {
    clienttaskExportTask({ taskId: row.id }).then((res) => {
        if (res) {
            const url = window.URL.createObjectURL(new Blob([res]));
            const link = document.createElement('a');

            link.href = url;
            link.setAttribute('download', `${row.taskName}_任务.xlsx`); // 文件名称
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url); // 释放掉blob对象
            ElMessage.success("导出成功");
        }
    }).catch(() => {
        ElMessage.error("导出失败");
    });
};

const onAddEqui = (row) => {
    router.push({
        name: "taskEquipmentList",
        query: {
            taskId: row.id,
            taskName: row.taskName
        },
    });
};

const onDel = (row) => {
    ElMessageBox.confirm("确定要删除该任务吗?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        await clienttaskDel({ ids: row.id });

        ElMessage.success("删除成功");
        searchForm.current = 1;
        search();
    })
        .catch((err) => {
            ElMessage({
                type: "info",
                message: "取消删除",
            });
        });
};

</script>


<style scoped>
.filterArea {
    display: flex;
    justify-content: space-between;
    padding-top: 10px;
}

.filterArea .el-select {
    width: 120px;
}

.el-table .el-link {
    margin-right: 10px;
}

.json-box {
    height: 100%;
    /* 或 400px / 60vh 随你 */
    overflow: auto;
    /* 关键：超出出现滚动条 */
}
</style>
